package middleware

import (
	"encoding/json"
	"fmt"
	"net/http"
	"time"

	"ip_server/logger"

	"github.com/gin-gonic/gin"
)

// 响应客户端中间件
func ResponseMiddleHandler(c *gin.Context) {
	c.Next()
	logid, _ := c.Get("logid")
	err, exist := c.Get("err")
	//如果发生错误，则返回错误信息
	if exist {
		errMap := map[string]interface{}{"code": -20, "message": err.(string)}
		c.JSON(http.StatusOK, errMap)
		resByte, err := json.Marshal(errMap)
		if err != nil {
			logger.Error("json marshal failed")
		}
		logger.Debug(logid, fmt.Sprintf("Response : %s", string(resByte)))
	} else { //否则返回正确结果
		res, exist := c.Get("res")
		if exist {
			c.JSON(http.StatusOK, res)
			resByte, err := json.Marshal(res)
			if err != nil {
				logger.Error("json marshal failed")
			}
			logger.Debug(logid, fmt.Sprintf("Response : %s", string(resByte)))
		}
	}
	startTime, _ := c.Get("start_time")
	timeEnd := time.Now()
	duration := timeEnd.Sub(startTime.(time.Time))
	logger.Debug(logid, "**************** Cost Duration : ", duration.String(), " ****************\r\n")
}
